<?php

declare(strict_types=1);
/**
 * 
 */
namespace WanZ\App\User\Logic;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Context\Context;
use Hyperf\Redis\RedisFactory;
use WanZ\App\User\Logic\Traits\UserTrait;
use EasyWeChat\Factory;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;

class WxLogic
{
    use UserTrait;
        
    /**
     * @Inject
     * @var CompanyLogic
     */
    private $companyLogic;   

    protected $loginKeyPrefix = 'temp:login:wx';
    protected static $miniConfig = [];

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;    


    public function login(string $authCode, int $companyId) : array
    {
        $userData = [];
        try {
            $result = $this->getUserWeChatIds($authCode, $companyId);

            $openid = $result['openid'] ?? '';
            $unionid = $result['unionid'] ?? '';
            if (empty($unionid)) {
                $userData = $this->getByWxMiniOpenId($openid);
            } else {
                $userData = $this->getByWxUnionId($unionid, $openid);
            }
        } catch (\Throwable $e) {
            $this->logger->error('getWxAuthLoginInfoError', [
                'errorMsg'        => $e->getMessage(),
                'errorCode'       => $e->getCode(),
                'site'            => $e->getFile() .'|'. $e->getLine(),
                'traceid'         => Context::get('traceid', ''),
                'client_tranceid' => Context::get('client_traceid', ''),
                'requestData'  => json_encode([
                    'auth_code'  => $authCode,
                    'company_id' => $companyId,
                    'appId'      => self::$miniConfig['app_id'] ?? '',
                    'platform'   => 'bicycles',
                ])
            ]);
            // $this->alarmHandle(['code' => $e->getCode()], ['log_tag' => 'getWxAuthLoginInfoError']);

            throw new CommonException(ErrorCode::SERVER_ERROR, $e->getMessage()); 
        }

        return $userData;
    }

    /**
     * 微信Ids
     * Cacheable(prefix="login:wx", ttl=600)
     */
    public function getUserWeChatIds(string $authCode, int $companyId): array
    {
        $cache = make(RedisFactory::class)->get('default');  
        $cacheKey = $this->loginKeyPrefix . ':' . $companyId . ':' . $authCode;
        $result = json_decode((string) $cache->get($cacheKey), true);
        if (! isset($result['openid']) || ! isset($result['unionid'])) {
            $config = $this->companyLogic->getPayConfig($companyId);
            // self::$miniConfig = [   //必要配置
            //     'app_id' => $config['wxMiniAppId'],
            //     'secret' => $config['wxMiniSecret'],
            //     'http'   => [
            //         'timeout' => 3, //3秒过期
            //     ],
            //     'response_type' => 'array',
            // ];
            // $result = Factory::miniProgram(self::$miniConfig)->auth->session($authCode);
            // if (! isset($result['openid'])) {
            //     throw new CommonException($result['errcode'] ?? '', '获取微信openid失败 ' . $result['errmsg'] ?? '');
            // }   
        }

        ## 上线需要注释掉以下2行代码
        $result['openid'] = 'oVUUv5dxqEs2hh8DDIz4-BszVFSc';
        $result['unionid'] = 'o-dX9wkmSbHbFWQAK8yqAtd63d4Y';

        $cache->set($cacheKey, json_encode($result, 256));
        $cache->expire($cacheKey, (int) config('login.bind_time', 240));

        return ['openid' => $result['openid'] ?? '', 'unionid' => $result['unionid'] ?? ''];
    }
    
    /**
     * @param $errorMsg
     * @param $reqData
     */
    // private function alarmHandle(array $errorMsg, array $reqData)
    // {
    //     \Swoft::trigger('error_alarm', null, [
    //         'type'     => 'wxLogin',
    //         'errorMsg' => $errorMsg,
    //         'params'   => $reqData,
    //     ]);
    // }    
}
